import React, { useEffect, useState } from 'react';
import { deleteNote, getNoteDetails } from '@/api/programmingNotes'
import { QuestionCircleOutlined } from '@ant-design/icons';
import Style from "./index.module.scss";
import { useRouter } from 'next/router';
import { Popconfirm, message } from 'antd';

const ProgrammingNotesDetail: React.FC = () => {
  const router = useRouter()
  const [messageApi, contextHolder] = message.useMessage();

  const [noteDetail, setNoteDetail] = useState({
    title: '',
    content: '',
    author: '',
    createTime: '',
    modifyTime: '',
  })

  useEffect(() => {
    getNoteDetailsById();
  }, [])

  // 获取笔记详情
  const getNoteDetailsById = () => {
    const id = getId();
    if (!id) return;
    getNoteDetails({ id: id }).then(res => {
      const {
        code = '000'
      } = res?.data ?? {}
      if (code === '200') {
        const resNoteDetail = res?.data.body ?? {}
        setNoteDetail(resNoteDetail)
      }
    })
  }

  // 跳转到编辑页面
  const gotoEdit = () => {
    const id = getId();
    router.push({
      pathname: '/system/programmingNotes/form',
      query: { id }
    },)
  }

  // 获取id
  const getId = () => {
    const href = location.href
    let query = href.substring(href.indexOf("?") + 1);
    const id = query.split('=')[1]
    return id;
  }

  // 删除笔记
  const handleDelete = () => {
    const id = getId();
    deleteNote({ id }).then(res => {
      const {
        code = '000'
      } = res?.data ?? {}
      if (code === '200') {
        messageApi.success('删除成功！');
        router.push({
          pathname: '/system/programmingNotes',
          query: { id }
        },)
      }
    })
  }

  return (
    <div className={Style.programming_detail}>
      <div className='note_page'>
        <span className='title'>{noteDetail.title}</span>
        <span className='author'>作者：{noteDetail.author}</span>
        <div className='line'></div>
        <div dangerouslySetInnerHTML={{ __html: noteDetail.content }} className='content'></div>
        <div className='time'>
          <span className='createTime'>创建日期：{noteDetail.createTime}</span>
          <span className='modifyTime'>修改日期：{noteDetail.modifyTime}</span>
        </div>
      </div>
      <div className='opration'>
        <div className='pencile' onClick={gotoEdit}>
          <div className='body'>
            编  辑
          </div>
          <div className='head'></div>
        </div>

        <Popconfirm
          title={noteDetail.title}
          description="是否确认删除此笔记?"
          icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
          onConfirm={handleDelete}
        >
          <div className='eraser'>
            <div className='head'></div>
            <div className='body'>
              删  除
            </div>
          </div>
        </Popconfirm>
      </div>
    </div>
  )
};

export default ProgrammingNotesDetail;
